<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="应用名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="应用名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="应用名称" prop="name"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column label="更新时间" prop="updateTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="320">
          <template #default="scope">
            <el-button type="warning" size="small" link @click="openDialog(scope.row.id)"><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button type="success" size="small" link @click="uploadZipFile(scope.row.id)"><i class="el-icon-upload2"></i> 上传应用文件</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 字典表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="80%"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="输入参数" prop="runArgsContent">
          <codemirror class="runArgsContent" ref="codemirrorRunEdit" v-model="runArgsContent" :options="cmOptions" />
        </el-form-item>
        <el-form-item label="输出参数" prop="retArgsContent">
          <codemirror class="runArgsContent" ref="codemirrorRetEdit" v-model="retArgsContent" :options="cmOptions" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="viewFileVisible" title="上传应用文件" width="300px" :close-on-click-modal="false">
      <el-upload
        class="upload-dialog"
        ref="upload"
        :action="uploadAction"
        :show-file-list="false"
        :on-change="submitUpload"
        :on-success="uploadFileSuccess"
        :headers="headers"
        :auto-upload="false"
      >
        <el-button slot="trigger" style="margin-left: 5px" type="success">上传输出文件（zip）</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
		</el-dialog>

  </div>
</template>

<script>

import dfApplicationApi from '@/api/analysis/application'
import { formatDate } from '@/utils/formatTime'
import { codemirror } from 'vue-codemirror';
import 'codemirror/lib/codemirror.css';
import { Session } from '@/utils/storage';
import 'codemirror/mode/javascript/javascript.js';
import "codemirror/mode/markdown/markdown.js";
import 'codemirror/mode/css/css.js';
import 'codemirror/mode/vue/vue.js';
import './setting.js';
export default {
	name: 'dictIndex',
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      cmOptions: {
				tabSize: 2, // tab
				styleActiveLine: true,
				lineNumbers: true, // 换行操作
				lineWrapping: true, // 换行操作
				styleSelectedText: true,
				line: true,
				foldGutter: true,
				gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
				highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
				mode: 'application/json',
				hintOptions: {
					completeSingle: false,
				},
				keyMap: 'sublime',
				matchBrackets: true,
				showCursorWhenSelecting: true,
				theme: 'monokai',
				// theme: 'solarized',
				extraKeys: {},
			},

      runArgsContent: '',
      retArgsContent: '',

      headers: {},
      uploadAction: '',
      viewFileVisible: false,
		};
	},
  mounted() {
		this.headers = {
			Authorization: 'Bearer ' + localStorage.getItem('token'),
		};
	},
  methods: {
    submitUpload () {
      this.$refs.upload.submit();
    },
    uploadFileSuccess () {
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.viewFileVisible = false;
    },
    uploadZipFile (id) {
      this.$confirm('上传应用文件后，将覆盖应用原有的输出参数Json, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.viewFileVisible = true;
        if (process.env.NODE_ENV === 'production') {
          this.uploadAction = 'https://w66h994817.zicp.fun/cloud-gateway/service-platform/df-application/upload-zip/' + id;
        } else {
          this.uploadAction = 'http://192.168.10.29:30000/service-platform/df-application/upload-zip/' + id;
        }
      }).catch(() => {         
      });
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      dfApplicationApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      this.formData.runArgsContent = this.runArgsContent;
      this.formData.retArgsContent = this.retArgsContent;
      if (this.formData.id) {
        dfApplicationApi.update(this.formData).then((res) => {
          this.$message({message: '数据应用更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        dfApplicationApi.add(this.formData).then((res) => {
          this.$message({message: '数据应用添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑应用');
        dfApplicationApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;
          this.runArgsContent = data.runArgsContent;
          this.retArgsContent = data.retArgsContent;
        });
      } else {
        this.$set(this.dialog, 'title', '新增应用');
        that.formData = {};
        this.runArgsContent = '';
        this.retArgsContent = '';
      }
    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dfApplicationApi.delete(id).then((res) => {
            this.$message({message: '数据应用删除成功！', type: 'success'});
            this.handleQuery();
          });
        }).catch(() => {         
        });
        
      } else {
        this.$message.error('暂不支持批量删除数据应用！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
/deep/.runArgsContent .CodeMirror-line {
  line-height: 15px !important;
}
/deep/.runArgsContent .CodeMirror-linenumber {
  line-height: 15px !important;
}
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>